package me.pppploi8.webmcs.task;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;

import me.pppploi8.webmcs.minecraft.server.core.McServerCore;

/**
 * 计划任务，类似于McServerFactory功能，于session关联即可实现多用户管理，但是因安全问题暂不支持
 * @author pppploi8
 *
 */
public abstract class TaskManageFactory {
	private static TaskManage taskManage;
	
	public static TaskManage createTaskManage(McServerCore msc){
		if (taskManage == null){
	    	TaskManage task = new TaskManage();
	    	task.setMcServerCore(msc);
	    	//根据配置文件构造TaskManage对象
	    	try{
	    		File file = new File(msc.getServerPath().getPath() + "/task");
	    		File[] files = file.listFiles();
	    		for(File f : files){
	    			if (f.isFile() && f.getName().toLowerCase().endsWith(".task")){
						 Properties p = new Properties();
						 InputStream is = new FileInputStream(f);
						 p.load(is);
						 is.close();
	    		         Map<String,String> map = new TreeMap<String,String>();
	    		         map.put("type", p.getProperty("type"));
	    		         map.put("content", p.getProperty("content"));
	    		         map.put("time", p.getProperty("time"));
						 map.put("exectype", p.getProperty("exectype"));
						 try{
							 task.addTask(task.createTask(f.getName().substring(0, f.getName().length()-5), map),false);
						 }catch(Exception e){
							 f.delete();
						 }
	    			}
	    		}
	    	}catch(Exception e){}
	    	taskManage = task;
		}
		return taskManage;
	}
	
	public static TaskManage getTaskManage(){
		return taskManage;
	}
}
